import axios from 'axios';
import Apis from '../apis/Apis';
import {ToastAndroid} from 'react-native';
const instance = axios.create({
  baseURL: 'http://10.9.86.54:7001',
  timeout: 10 * 1000,
});

instance.interceptors.response.use(
  response => response,
  error => {
    const {response} = error;

    if (response) {
      const {status} = response;
      if (status >= 500) {
        ToastAndroid.show('服务器错误', ToastAndroid.LONG);
      } else if (status === 400) {
        ToastAndroid.show('请求参数错误', ToastAndroid.LONG);
      } else if (status === 401) {
        ToastAndroid.show('登录过期错误', ToastAndroid.LONG);
      } else if (status === 403) {
        ToastAndroid.show('访问权限错误', ToastAndroid.LONG);
      } else {
        ToastAndroid.show('未知错误', ToastAndroid.LONG);
      }
    } else {
      ToastAndroid.show('网络错误', ToastAndroid.LONG);
    }
    return Promise.reject(error);
  },
);

const request = (name: string, params: any) => {
  const api = Apis[name];
  const {url, method} = api;
  if (method === 'GET') {
    return get(url, params);
  } else {
    return post(url, params);
  }
};

/**
 * get 请求
 * @param url 请求地址
 * @param params 请求参数
 * @returns 请求后的response
 */
const get = (url: string, params: any) => {
  return instance.get(url, {params});
};

/**
 * get 请求
 * @param url 请求地址
 * @param params 请求参数
 * @returns 请求后的response
 */
const post = (url: string, params: any) => {
  return instance.post(url, params);
};

export {request};
